//
//  HandCarVC.m
//  saler-ios
//
//  Created by 王亚陆 on 17/9/13.
//  Copyright © 2017年 sayimba. All rights reserved.
//

#import "HandCarVC.h"
#import "CustomTextField.h"
@interface HandCarVC ()
{
    UIImageView * nav;
    NSMutableDictionary * dataDic;

}
@property (nonatomic,strong) UIImageView * backView1;
@property (nonatomic,strong) CustomTextField * namefield;
@property (nonatomic,strong) CustomTextField * iphonefield;
@property (nonatomic,strong) CustomTextField * addressfield;

@end

@implementation HandCarVC



- (instancetype)init
{
    self = [super init];
    if (self) {
        self.dicSouce = [[NSMutableDictionary alloc]init];
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    nav = [self createNav:@"交车信息"];
    [self.view addSubview:nav];
    self.view.backgroundColor = UIviewBackColor;
    
    
    dataDic = [[NSMutableDictionary alloc]init];
    
    
    NSString * isDeliv = [NSString stringWithFormat:@"%@",self.dicSouce[@"isDeliv"]];
    
    if ([isDeliv isEqualToString:@"1"]) {
        [dataDic setObject:@"1" forKey:@"isDeliv"];
    }else{
        [dataDic setObject:@"0" forKey:@"isDeliv"];
    }

    
    
    
    [dataDic setObject:@"" forKey:@"people"];
    [dataDic setObject:@"" forKey:@"phone"];
    [dataDic setObject:@"" forKey:@"address"];

    
    
    self.backView1 = [[UIImageView alloc]init];
    self.backView1.backgroundColor = WhiteColor;
    self.backView1.userInteractionEnabled = YES;
    [self.view addSubview:self.backView1];
    
    
    
    
    [self.backView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left).with.offset(10*kWidth);
        make.top.mas_equalTo(nav.mas_bottom).with.offset(10*kHeight);
        make.size.mas_equalTo(CGSizeMake(Main_Width-20*kWidth, 300*kHeight));
    }];
    
    
    UILabel * label1 = [UILabel createUIlabel:@"交车方式" andFont:FontOfSize14 andColor:carScrollColor];
    [self.backView1 addSubview:label1];
    [label1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.backView1.mas_left).with.offset(23*kWidth);
        make.top.mas_equalTo(self.backView1.mas_top).with.offset(20*kHeight);
    }];
    
    
    
    UIButton * SinceYesBtn = [self createBtn:@"物流点自提" andBorderColor:YellowColor andFont:FontOfSize12 andTitleColor:YellowColor andBackColor:WhiteColor];
    [SinceYesBtn setTitleColor:YellowColor forState:UIControlStateNormal];
    SinceYesBtn.tag = 100;
    
    [SinceYesBtn addTarget:self action:@selector(pressSince:) forControlEvents:UIControlEventTouchUpInside];
    [self.backView1 addSubview:SinceYesBtn];
    [SinceYesBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.backView1.mas_left).with.offset(23*kWidth);
        make.top.mas_equalTo(label1.mas_bottom).with.offset(17*kHeight);
        make.size.mas_equalTo(CGSizeMake(80*kWidth, 23*kHeight));
    }];
    UIButton *  SinceNoBtn= [self createBtn:@"送车上门" andBorderColor:LineGrayColor andFont:FontOfSize12 andTitleColor:littleBlackColor andBackColor:WhiteColor];
    [self.backView1 addSubview:SinceNoBtn];
    SinceNoBtn.tag = 200;
    [SinceNoBtn addTarget:self action:@selector(pressSince:) forControlEvents:UIControlEventTouchUpInside];
    [SinceNoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(SinceYesBtn.mas_right).with.offset(10*kWidth);
        make.centerY.mas_equalTo(SinceYesBtn.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(70*kWidth, 23*kHeight));
    }];
    
    
    
    UIView * lineView= [[UIView alloc]init];
    lineView.backgroundColor = LineColor;
    [self.backView1 addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.backView1.mas_left);
        make.right.mas_equalTo(self.backView1.mas_right);
        make.centerY.mas_equalTo(SinceNoBtn.mas_bottom).with.offset(20*kHeight);
        make.height.mas_equalTo(0.5*kHeight);
    }];
    
    
    if (![dataDic[@"isDeliv"] isEqualToString:@"0"]) {
        
        SinceNoBtn.layer.borderColor = YellowColor.CGColor;
        [SinceNoBtn setTitleColor:YellowColor forState:UIControlStateNormal];
        SinceYesBtn.layer.borderColor = LineGrayColor.CGColor;
        [SinceYesBtn setTitleColor:littleBlackColor forState:UIControlStateNormal];
        
    }

    
    
    
    UILabel * label2 = [UILabel createUIlabel:@"收车联系人" andFont:FontOfSize14 andColor:carScrollColor];
    [self.backView1 addSubview:label2];
    [label2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(label1.mas_left);
        make.top.mas_equalTo(lineView.mas_bottom).with.offset(10*kHeight);
    }];
    
    
    
    UILabel * namelabel = [UILabel createUIlabel:@"姓 名" andFont:FontOfSize14 andColor:UIlabelColor];
    [self.backView1 addSubview:namelabel];
    [namelabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.backView1.mas_left).with.offset(25*kWidth);
        make.top.mas_equalTo(label2.mas_bottom).with.offset(20*kHeight);
    }];
    
    
//    [postDic setObject:dic[@"people"] forKey:@"destContact"];
//    [postDic setObject:dic[@"phone"] forKey:@"destPhone"];
//    [postDic setObject:dic[@"address"] forKey:@"destAddr"];
//    [postDic setObject:dic[@"isDeliv"] forKey:@"isDeliv"];

    
   self.namefield = [self createField:@"请输入姓名" andTag:1 andFont:FontOfSize14];
    [self.namefield addTarget:self action:@selector(textFieldWithText:) forControlEvents:UIControlEventEditingChanged];
    
    NSString * nameStr = [NSString stringWithFormat:@"%@",self.dicSouce[@"destContact"]];
    
    if (nameStr.length > 0) {
        self.namefield.text = nameStr;
        [dataDic setObject:nameStr forKey:@"people"];
    }
    
    
    
    [self.backView1 addSubview:self.namefield];
    [self.namefield mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(label2.mas_right);
        make.centerY.mas_equalTo(namelabel.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(Main_Width/2, 25*kHeight));
    }];
    
    UIImageView * people = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"home_people"]];
    people.tag = 1000;
    [self.backView1 addSubview:people];
    [people mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.backView1.mas_right).with.offset(-25*kWidth);
        make.centerY.mas_equalTo(namelabel.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(16*kWidth, 16*kHeight));
    }];
    
    UIButton * iphoneBtn = [UIButton createUIbutton:@"" andFont:1 andColor:nil];
    [iphoneBtn addTarget:self action:@selector(pressNumber) forControlEvents:UIControlEventTouchUpInside];
    [self.backView1 addSubview:iphoneBtn];
    [iphoneBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.backView1.mas_right).with.offset(-5*kWidth);
        make.centerY.mas_equalTo(namelabel.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(50*kWidth, 40*kHeight));
    }];
    
    
    UIView * lineView2= [[UIView alloc]init];
    lineView2.backgroundColor = LineColor;
    [self.backView1 addSubview:lineView2];
    [lineView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.namefield.mas_left);
        make.centerY.mas_equalTo(namelabel.mas_centerY).with.offset(15*kHeight);
        make.height.mas_equalTo(0.5*kHeight);
        make.right.mas_equalTo(self.backView1.mas_right);
    }];
    
    
    UILabel * iphonelabel = [UILabel createUIlabel:@"电 话" andFont:FontOfSize14 andColor:UIlabelColor];
    [self.backView1 addSubview:iphonelabel];
    [iphonelabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.backView1.mas_left).with.offset(25*kWidth);
        make.top.mas_equalTo(namelabel.mas_bottom).with.offset(30*kHeight);
    }];
    
    self.iphonefield = [self createField:@"请输入电话" andTag:2 andFont:FontOfSize14];
    [self.iphonefield addTarget:self action:@selector(textFieldWithText:) forControlEvents:UIControlEventEditingChanged];
    
    NSString * iphoneStr = [NSString stringWithFormat:@"%@",self.dicSouce[@"destPhone"]];
    
    if (iphoneStr.length > 0) {
        self.iphonefield.text = iphoneStr;
        [dataDic setObject:iphoneStr forKey:@"phone"];
        
    }
    
    
    [self.backView1 addSubview:self.iphonefield];
    [self.iphonefield mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(label2.mas_right);
        make.centerY.mas_equalTo(iphonelabel.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(Main_Width/2, 25*kHeight));
    }];
    
    
    UIView * lineView3= [[UIView alloc]init];
    lineView3.backgroundColor = LineColor;
    [self.backView1 addSubview:lineView3];
    [lineView3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.iphonefield.mas_left);
        make.centerY.mas_equalTo(iphonelabel.mas_centerY).with.offset(15*kHeight);
        make.height.mas_equalTo(0.5*kHeight);
        make.right.mas_equalTo(self.backView1.mas_right);
    }];
    
    
    UILabel * addresslabel = [UILabel createUIlabel:@"详细地址" andFont:FontOfSize14 andColor:UIlabelColor];
    [self.backView1 addSubview:addresslabel];
    [addresslabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.backView1.mas_left).with.offset(25*kWidth);
        make.top.mas_equalTo(iphonelabel.mas_bottom).with.offset(30*kHeight);
    }];
    
    self.addressfield = [self createField:@"请输入详细地址" andTag:3 andFont:FontOfSize14];
    [self.addressfield addTarget:self action:@selector(textFieldWithText:) forControlEvents:UIControlEventEditingChanged];
    
    NSString * addressStr = [NSString stringWithFormat:@"%@",self.dicSouce[@"destAddr"]];
    
    if (addressStr.length > 0) {
        self.addressfield.text = addressStr;
        
        [dataDic setObject:addressStr forKey:@"address"];
        
    }

    
    [self.backView1 addSubview:self.addressfield];
    [self.addressfield mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(label2.mas_right);
        make.centerY.mas_equalTo(addresslabel.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(Main_Width/2, 25*kHeight));
    }];
    
    UIView * lineView4= [[UIView alloc]init];
    lineView4.backgroundColor = LineColor;
    [self.backView1 addSubview:lineView4];
    [lineView4 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.iphonefield.mas_left);
        make.centerY.mas_equalTo(addresslabel.mas_centerY).with.offset(15*kHeight);
        make.height.mas_equalTo(0.5*kHeight);
        make.right.mas_equalTo(self.backView1.mas_right);
    }];

    
    
    
    UIButton * confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [confirmBtn setTitle:@"确定" forState:UIControlStateNormal];
    [confirmBtn setTitleColor:WhiteColor forState:UIControlStateNormal];
    [confirmBtn addTarget:self action:@selector(pressConfirmBtn) forControlEvents:UIControlEventTouchUpInside];
    LRViewBorderRadius(confirmBtn, 5, 0.5, YellowColor);
    confirmBtn.backgroundColor = YellowColor;
    [self.view addSubview:confirmBtn];
    [confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(355*kWidth, 50*kHeight));
        make.top.mas_equalTo(self.backView1.mas_bottom).with.offset(37*kHeight);
    }];

}

-(void)pressConfirmBtn{
    
    
    
    if(_callBackPickCarInfor){
        _callBackPickCarInfor(dataDic);
    }

    
    [self.navigationController popViewControllerAnimated:YES];
    
    NSLog(@"点击确定");
    
}

-(void)pressNumber{
    
    //让用户给权限,没有的话会被拒的各位
    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    if (status == CNAuthorizationStatusNotDetermined) {
        CNContactStore *store = [[CNContactStore alloc] init];
        [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (error) {
                NSLog(@"weishouquan ");
            }else
            {
                NSLog(@"chenggong ");//用户给权限了
                CNContactPickerViewController * picker = [CNContactPickerViewController new];
                picker.delegate = self;
                picker.displayedPropertyKeys = @[CNContactPhoneNumbersKey];//只显示手机号
                [self presentViewController: picker  animated:YES completion:nil];
            }
        }];
    }
    
    if (status == CNAuthorizationStatusAuthorized) {//有权限时
        CNContactPickerViewController * picker = [CNContactPickerViewController new];
        picker.delegate = self;
        picker.displayedPropertyKeys = @[CNContactPhoneNumbersKey];
        [self presentViewController: picker  animated:YES completion:nil];
    }
    else{
        
        //        NSURL *url = [NSURL URLWithString:@"App-prefs:root=ACCOUNT_SETTINGS"];
        //
        //
        //        if ([[UIApplication sharedApplication] canOpenURL:url]) {
        //
        //            [[UIApplication sharedApplication] openURL:url];
        //
        //        }
        
        [self createUIAlertController:@"您未开启通讯录权限,请前往设置-隐私-通讯录开启"];
    }
    
    
}

-(void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact{
    
    CNPhoneNumber * num = nil;
    NSString * name = nil;
    NSString * number = nil;
    
    if (contact.phoneNumbers.count >0) {
        num = contact.phoneNumbers[0].value;
        name = [NSString stringWithFormat:@"%@%@",contact.familyName,contact.givenName];
        number = [NSString stringWithFormat:@"%@",[num valueForKey:@"digits"]];
        UIImageView * image = [self.backView1 viewWithTag:1000];
        image.image = [UIImage imageNamed:@"people"];
        
        
    }else{
        
        name = [NSString stringWithFormat:@"%@%@",contact.familyName,contact.givenName];
        number = @"";
    }
    
    UITextField * field0 = (UITextField*)[self.backView1 viewWithTag:1 ];
    UITextField * field1 = (UITextField*)[self.backView1 viewWithTag:2];
    field0.text = name;
    field1.text = number;
    
    
    [dataDic setObject:name forKey:@"people"];
    [dataDic setObject:number forKey:@"phone"];
    
}


-(void)textFieldWithText:(UITextField *)textField{
    //500 501 502 503
    UITextField * field = (UITextField*)textField;
    switch (textField.tag) {
        case 1://联系人
            if ([self textField:field shouldChangeCharactersInRange:NSMakeRange(0, 0) replacementString:@""]) {
                
                NSLog(@"联系人");

                [dataDic setValue:field.text forKey:@"people"];
                
            }
            break;
        case 2: //联系电话
            if ([self textField:field shouldChangeCharactersInRange:NSMakeRange(0, 0) replacementString:@""]) {
                NSLog(@"联系电话");

                [dataDic setValue:field.text forKey:@"phone"];
                
            }
            break;
        case 3: //详细地址
            if ([self textField:field shouldChangeCharactersInRange:NSMakeRange(0, 0) replacementString:@""]) {
                
                
                NSLog(@"详细地址");
                
                [dataDic setValue:field.text forKey:@"address"];
                
            }
            break;

            
        default:
            break;
    }
    
}







-(void)pressSince:(UIButton*)sender{

    UIButton * big = (UIButton*)[self.view viewWithTag:100];
    UIButton * small = (UIButton*)[self.view viewWithTag:200];
    if (sender.tag == 100) {
        big.layer.borderColor = YellowColor.CGColor;
        [big setTitleColor:YellowColor forState:UIControlStateNormal];
        small.layer.borderColor = LineGrayColor.CGColor;
        [small setTitleColor:littleBlackColor forState:UIControlStateNormal];
        
        [dataDic setObject:@"0" forKey:@"isDeliv"];
        
    }else{
        small.layer.borderColor = YellowColor.CGColor;
        [small setTitleColor:YellowColor forState:UIControlStateNormal];
        big.layer.borderColor = LineGrayColor.CGColor;
        [big setTitleColor:littleBlackColor forState:UIControlStateNormal];
        [dataDic setObject:@"1" forKey:@"isDeliv"];

    }


    

}

-(CustomTextField*)createField:(NSString*)placeholder andTag:(NSInteger)tag andFont:(double)font{
    
    NSMutableAttributedString * placeH = [[NSMutableAttributedString alloc]initWithString:placeholder];
    
    CustomTextField * field =[[CustomTextField alloc]init];
    field.frame = CGRectMake(84*kWidth, 0, Main_Width-100*kWidth, 43*kWidth);
    field.delegate = self;
    field.font = Font(font);
    field.tag = tag;

    [field setValue:[UIFont boldSystemFontOfSize:font]forKeyPath:@"_placeholderLabel.font"];
    
    [placeH addAttribute:NSFontAttributeName
                   value:[UIFont boldSystemFontOfSize:16]
                   range:NSMakeRange(0, placeholder.length)];
    field.attributedPlaceholder = placeH;
    
    field.clearButtonMode = UITextFieldViewModeWhileEditing;
    field.userInteractionEnabled = YES;
    field.textAlignment = NSTextAlignmentLeft;
    field.returnKeyType = UIReturnKeyDone;
    CGFloat width = field.frame.size.width;
    CGFloat height = field.frame.size.height;
    //控制placeHolder的位置
    [field placeholderRectForBounds:CGRectMake(width/2, 0, width, height)];
    
    [field clearButtonRectForBounds:field.frame];
    
    return field;
}

-(UIButton*)createBtn:(NSString*)title andBorderColor:(UIColor*)BorderColor andFont:(CGFloat)Font andTitleColor:(UIColor*)titleColor andBackColor:(UIColor*)BackColor {
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.layer.borderWidth = 1;
    btn.layer.cornerRadius = 5;
    btn.backgroundColor = BackColor;
    btn.layer.borderColor = BorderColor.CGColor;
    btn.titleLabel.font = Font(Font);
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:TitleColor forState:UIControlStateNormal];
    return btn;
}


//触摸方法
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{
    for (UITextField * field in _backView1.subviews) {
        [field resignFirstResponder];
    }
}

//点击return按钮 键盘隐藏 这是协议中的方法
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //键盘隐藏 也就是让键盘取消第一响应者身份
    [textField resignFirstResponder];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{  //string就是此时输入的那个字符textField就是此时正在输入的那个输入框返回YES就是可以改变输入框的值NO相反
    
    if ([string isEqualToString:@"\n"])  //按会车可以改变
    {
        return YES;
    }
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
    
    if (textField.tag == 1) {
        
        if ([toBeString length] >25) {
            [self createUIAlertController:@"联系人输入不能超过25个字符"];
            return NO;
        }
    }else if (textField.tag == 2){
        if ([toBeString length] >11) {
            [self createUIAlertController:@"联系电话输入不能超过11个字符"];
            return NO;
        }
    }else{
        if ([toBeString length] >50) {
            [self createUIAlertController:@"详细地址不能超过50个字符"];
        }
    }
    
    return YES;
}


-(void)createUIAlertController:(NSString*)title

{
    UIAlertController * alert =[UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * action =[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction * action1 =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:action1];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
